﻿using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyServer.Mixture
{
    /// <summary>
    /// 为混合协议数据收发提供协议存储
    /// </summary>
    public static class ProtocolPool
    {
        /// <summary>
        /// 协议列表
        /// </summary>
        private static ArrayList ProtocolList = ArrayList.Synchronized(new ArrayList());

        /// <summary>
        /// 注册协议
        /// </summary>
        /// <param name="Protocol">要注册的协议</param>
        /// <returns>一个值，表示是否注册成功</returns>
        public static bool RegisterProtocol(IProtocolItem Protocol, object Setting)
        {
            IProtocolItem[] Items = (IProtocolItem[])ProtocolList.ToArray();
            lock (Items)
            {
                foreach (IProtocolItem item in ProtocolList.ToArray())
                {
                    if (item.Guid == Protocol.Guid)
                    {
                        return false;
                    }
                }
                if (Protocol.Init(Setting))
                {
                    ProtocolList.Add(Protocol);
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        /// <summary>
        /// 根据GUID获取协议实例
        /// </summary>
        /// <param name="Guid">协议的GUID</param>
        /// <returns>获取到的协议实例</returns>
        public static IProtocolItem GetProtocol(string Guid)
        {
            IProtocolItem[] Items = (IProtocolItem[])ProtocolList.ToArray();
            lock (Items)
            {
                foreach (IProtocolItem item in Items)
                {
                    if (item.Guid == Guid)
                    {
                        return item;
                    }
                }
                return null;
            }
        }
        /// <summary>
        /// 获取已注册的协议的数组
        /// </summary>
        /// <returns></returns>
        public static IProtocolItem[] GetList()
        {
            return ((IProtocolItem[])ProtocolList.ToArray());
        }
    }
}
